const router = require('koa-router')()
const connection = require('./db'); // 导入数据库连接对象
const fs = require('fs');
const path = require('path');
// 定义 GET 请求处理函数
router.get("/getteacherhomework", async (ctx, next) => {
    let request = ctx.request;
    let reqquery = request.query;
    const {id} = reqquery;
    console.log(id); // 输出请求中的页码参数
    const query = `SELECT * FROM \`homework-teacher\` WHERE courseid = '${id}'`;

    try {
        // 使用 Promise 封装数据库查询
        const queryAsync = () => {
            return new Promise((resolve, reject) => {
                connection.query(query, function (error, results, fields) {
                    if (error) {
                        reject(error);
                    } else {
                        resolve(results);
                    }
                });
            });
        };

        // 使用 await 等待查询结果
        const list = await queryAsync();
        const parsedList = JSON.parse(JSON.stringify(list)); // 解析数据库查询结果为 JSON 格式
        console.log(list);
        const page = reqquery.page;
        const perpage = reqquery.perpage;
        console.log('页码:', page, '每页数量:', perpage);
        ctx.body = {
            list: parsedList,
            length: parsedList.length
        };
    } catch (error) {
        // 处理错误
        console.error(error);
        ctx.status = 500;
        ctx.body = "Internal Server Error";
    }
});

router.post('/addhomework', async (ctx, next) => {
    // 处理 GET 请求
    console.log('收到针对 /addhomework 的 GET 请求');
    // 使用 ctx.query 访问查询参数
    const values = ctx.request.body.values;
    const requestData = ctx.request.body;
    console.log('收到的前端数据：',values);
    try {
      // 执行数据库更新操作
      const addQuery = 'INSERT INTO  \`homework-teacher\` SET ?';
      await connection.query(addQuery, values);
   
  
      // 检查是否成功更新数据
      console.log('成功添加数据');
      ctx.body = '成功添加数据';
    } catch (error) {
      console.error('添加数据时出现错误：', error);
      ctx.status = 500;
      ctx.body = '添加数据时出现错误';
    }
  });

  router.post('/homeworkupload', async (ctx) => {
    const file = ctx.request.files.file; // 文件将被存储在ctx.request.files中
    console.log(file);
    // 执行适当的文件处理逻辑
    const newFilename = file['newFilename'];
    console.log('新文件名:', newFilename);
    ctx.body = {
        message: 'File uploaded successfully',
        newFilename: newFilename
    };
  })

  router.delete("/deletehomework/:id/:img", async (ctx, next) => {
    const Id = ctx.params.id; // 获取URL中的id参数
    const filenames = ctx.params.img; // 获取URL中的img参数
    console.log('新文件名:', filenames);
    const splitFilenames = filenames.split(", "); // 按逗号和空格分割
    const normalFilenames = splitFilenames.map(filename => {
        return filename.trim(); // 去除可能存在的空格
    });
    console.log(normalFilenames);
    normalFilenames.forEach(filename => {
        const filePath = './routes/uploads/' + filename;
        
        fs.unlink(filePath, (err) => {
            if (err) {
                console.error(`文件 ${filePath} 删除失败`, err);
                return;
            }
            console.log(`文件 ${filePath} 删除成功`);
        });
    });

   try {
        const deleteQuery = `DELETE FROM \`homework-teacher\` WHERE id = ?`;

        // 使用 Promise 封装数据库删除操作
        const deleteAsync = () => {
            return new Promise((resolve, reject) => {
                connection.query(deleteQuery, [Id], function (error, results, fields) {
                    if (error) {
                        reject(error);
                    } else {
                        resolve(results);
                    }
                });
            });
        };

        // 使用 await 等待删除操作的结果
        const deleteResult = await deleteAsync();

        if (deleteResult.affectedRows > 0) {
            console.log(`teacher with ID ${Id} deleted successfully`);
            ctx.body = 'teacher deleted successfully';
        } else {
            console.log(`teacher with ID ${Id} not found`);
            ctx.status = 404; // 资源未找到
            ctx.body = 'teacher not found';
        }
    } catch (error) {
        // 处理错误
        console.error(`Error deleting teacher with ID ${Id}: ${error.message}`);
        ctx.status = 500; // 内部服务器错误
        ctx.body = 'Error deleting teacher';
    }
});

router.delete("/deletehomeworks/:id", async (ctx, next) => {
  const id = ctx.params.id; // 获取URL中的id参数

  try {
      const deleteQuery = `DELETE FROM \`homework-teacher\` WHERE id = ?`;
      const results = await connection.query(deleteQuery, [id]); // 执行SQL查询
      console.log(`Deleted teacher with ID ${id}`);
      ctx.body = 'Teacher deleted';
  } catch (error) {
      // 处理错误
      console.error(`Error deleting teacher with ID ${id}: ${error.message}`);
      ctx.status = 500; // 内部服务器错误
      ctx.body = 'Error deleting teacher';
  }
});


router.post('/changehomework', async (ctx, next) => {
    // 处理 GET 请求
    console.log('收到针对 /homework 的 GET 请求');
    // 使用 ctx.query 访问查询参数
    const Id = ctx.request.body.Id;
    const values = ctx.request.body.values;
    const requestData = ctx.request.body;
    console.log('收到的前端数据：', Id,values);
    try {
      // 执行数据库更新操作
      const updateQuery = 'UPDATE \`homework-teacher\` SET ? WHERE id = ?';
      await connection.query(updateQuery, [values, Id]);
  
      // 检查是否成功更新数据
      console.log('成功更新数据');
      ctx.body = '成功更新数据';
    } catch (error) {
      console.error('更新数据时出现错误：', error);
      ctx.status = 500;
      ctx.body = '更新数据时出现错误';
    }
  });


  router.post('/studenthomework', async (ctx, next) => {
    // 处理 GET 请求
    // 使用 ctx.query 访问查询参数
    const values = ctx.request.body.values;
    const requestData = ctx.request.body;
    console.log('收到的前端数据：',values);
    try {
      // 执行数据库更新操作
      const addQuery = 'INSERT INTO  \`homework-student\` SET ?';
      await connection.query(addQuery, values);
   
  
      // 检查是否成功更新数据
      console.log('成功添加数据');
      ctx.body = '成功添加数据';
    } catch (error) {
      console.error('添加数据时出现错误：', error);
      ctx.status = 500;
      ctx.body = '添加数据时出现错误';
    }
  });


  
  router.post('/delimg', async (ctx, next) => {
    const { imageToDelete ,Id} = ctx.request.body;
  console.log(Id)
    try {
        
      const imageNames = imageToDelete.split(', '); // 将逗号和空格分隔的图片文件名拆分成数组
  
      imageNames.forEach(imageName => {
        const imagePath = path.join(__dirname, 'uploads', imageName); // 构建图片文件路径
        if (fs.existsSync(imagePath)) {
          fs.unlinkSync(imagePath); // 如果文件存在，则删除对应的图片文件
          console.log(`Deleted image: ${imageName}`);
        } else {
          console.log(`File not found: ${imageName}`);
        }
      });
  
      ctx.body = 'Images deleted successfully.';
    } catch (err) {
      console.error('Error deleting images:', err);
      ctx.status = 500;
      ctx.body = 'Failed to delete images.';
    }
    const updateQuery = 'UPDATE `homework-teacher` SET ? WHERE id = ?';
const updatedValues = { img: null }; // 将 img 字段设置为 NULL
await connection.query(updateQuery, [updatedValues, Id]);

  });
  

  router.get("/getstudenthomework", async (ctx, next) => {
    const { courseid, homeworkid } = ctx.request.query;
    console.log(courseid, homeworkid); // 输出请求中的页码参数
    const query = `SELECT * FROM \`homework-student\` WHERE courseid = '${courseid}' AND homeworkid = '${homeworkid}'`;

    try {
        // 使用 Promise 封装数据库查询
        const queryAsync = () => {
            return new Promise((resolve, reject) => {
                connection.query(query, function (error, results, fields) {
                    if (error) {
                        reject(error);
                    } else {
                        resolve(results);
                    }
                });
            });
        };

        // 使用 await 等待查询结果
        const list = await queryAsync();
        const parsedList = JSON.parse(JSON.stringify(list)); // 解析数据库查询结果为 JSON 格式
        console.log(list);
        
        const page = ctx.request.query.page; // 更新为 ctx.request.query.page
        const perpage = ctx.request.query.perpage; // 更新为 ctx.request.query.perpage
        console.log('页码:', page, '每页数量:', perpage);
        
        ctx.body = {
            list: parsedList,
            length: parsedList.length
        };
    } catch (error) {
        // 处理错误
        console.error(error);
        ctx.status = 500;
        ctx.body = "Internal Server Error";
    }
});

router.post('/correcthomework', async (ctx, next) => {
  // 处理 GET 请求
  console.log('收到针对 /homework 的 GET 请求');
  // 使用 ctx.query 访问查询参数
  const Id = ctx.request.body.Id;
  const values = ctx.request.body.values;
  const requestData = ctx.request.body;
  console.log('收到的前端数据：', Id,values);
  try {
    // 执行数据库更新操作
    const updateQuery = 'UPDATE \`homework-student\` SET ? WHERE id = ?';
    await connection.query(updateQuery, [values, Id]);

    // 检查是否成功更新数据
    console.log('成功更新数据');
    ctx.body = '成功更新数据';
  } catch (error) {
    console.error('更新数据时出现错误：', error);
    ctx.status = 500;
    ctx.body = '更新数据时出现错误';
  }
});



router.get("/getstuhomework", async (ctx, next) => {
  const { courseid, homeworkid ,studentid  } = ctx.request.query;
  console.log(courseid, homeworkid,studentid); // 输出请求中的页码参数
  const query = `SELECT * FROM \`homework-student\` WHERE courseid = '${courseid}' AND homeworkid = '${homeworkid}'AND studentid = '${studentid}'`;

  try {
      // 使用 Promise 封装数据库查询
      const queryAsync = () => {
          return new Promise((resolve, reject) => {
              connection.query(query, function (error, results, fields) {
                  if (error) {
                      reject(error);
                  } else {
                      resolve(results);
                  }
              });
          });
      };

      // 使用 await 等待查询结果
      const list = await queryAsync();
      const parsedList = JSON.parse(JSON.stringify(list)); // 解析数据库查询结果为 JSON 格式
      console.log(list);
      
      ctx.body = {
          list: parsedList,
      };
  } catch (error) {
      // 处理错误
      console.error(error);
      ctx.status = 500;
      ctx.body = "Internal Server Error";
  }
});
  

module.exports = router